﻿using SharpConfig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace BaiduActivePush
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        private static readonly HttpClient Client = new HttpClient();

        /// <summary>
        /// 产品名称
        /// </summary>
        private const string ProductName = "BaiduActivePush";

        /// <summary>
        /// 产品版本
        /// </summary>
        private const string Version = "1.0";

        /// <summary>
        /// 配置信息
        /// </summary>
        private Configuration _usercfg = new Configuration();


        //string sitemapPath = @"E:\Firefox_download\curl-7.54.1\I386\sitemap.xml";
        const string patternUrls = @"<loc>http://.*?</loc>";

        const string fileUrlsHaveCommit = "urlsHaveCommit.txt";
        const string fileUrls = "urls.txt";

        //已经转化并且提交的
        private readonly List<string> lstUrlsHaveCommit = new List<string>();
        //新转化的待提交的
        private readonly List<string> lstUrlsWaitCommit = new List<string>();
        private string strMsg;
        static MainWindow()
        {
            Client.DefaultRequestHeaders.UserAgent.ParseAdd(string.Format("{0}/{1}", ProductName, Version));
            Client.DefaultRequestHeaders.Host = "data.zz.baidu.com";
        }

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            chk_IsDefaultSite.Click += Chk_IsDefaultSite_Click;
            cb_Site.SelectionChanged += Cb_Site_SelectionChanged;

        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //配置加载
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "user.ini");
            if (File.Exists(path))
            {
                _usercfg = Configuration.LoadFromFile(path);
                var section = _usercfg["General"];
                //this.tb_Site.ItemsSource = section["site"].StringValueArray;
                foreach (var item in section["site"].StringValueArray)
                {
                    cb_Site.Items.Add(item);
                }
                foreach (var item in section["SitexmlPath"].StringValueArray)
                {
                    cb_SitexmlPath.Items.Add(item);
                }
                if (cb_Site.Items.Count > 0)
                {
                    if (cb_Site.Items.Contains(section["defaultsite"].StringValue))
                    {
                        cb_Site.SelectedItem = section["defaultsite"].StringValue;
                        chk_IsDefaultSite.IsChecked = true;
                        //选择Sitemap路径
                        //cb_SitexmlPath.SelectedIndex = 0;
                    }
                    else
                    {
                        cb_Site.SelectedIndex = 0;
                    }
                }

                if (cb_SitexmlPath.Items.Count > 0)
                {
                    if (cb_SitexmlPath.Items.Contains(section["defaultsitemapPath"].StringValue))
                    {
                        cb_SitexmlPath.SelectedItem = section["defaultsitemapPath"].StringValue;
                        chk_IsDefaultSitemapPath.IsChecked = true;
                       
                    }
                    else
                    {
                        cb_Site.SelectedIndex = 0;
                    }
                }

                //this.tb_Site.Text = section["site"].StringValue;
                tb_Token.Text = section["token"].StringValue;
                chk_IsOriginal.IsChecked = section["type"].StringValue == "original";
            }
            else
            {
                _usercfg = new Configuration();
            }
        }

        private void Cb_Site_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_usercfg == null || _usercfg["General"] == null || cb_Site.SelectedItem == null)
                return;
            var section = _usercfg["General"];
            chk_IsDefaultSite.IsChecked = cb_Site.SelectedItem.ToString() == section["defaultsite"].StringValue;

        }

        /// <summary>
        /// 添加网站
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddSite_Click(object sender, RoutedEventArgs e)
        {
            var win = new WindowAddSite { Owner = this };
            if (!(win.ShowDialog() ?? false)) return;
            cb_Site.Items.Add(win.NewSite);
            btn_SaveConfig_Click(sender, e);
        }


        /// <summary>
        /// 勾选默认网站
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chk_IsDefaultSite_Click(object sender, RoutedEventArgs e)
        {
            btn_SaveConfig_Click(sender, e);
        }

        /// <summary>
        /// 配置保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "user.ini");

                if (chk_IsDefaultSite.IsChecked ?? false)
                {
                    _usercfg["General"]["defaultsite"].StringValue = cb_Site.Text;
                }
                if (chk_IsDefaultSitemapPath.IsChecked ?? false)
                {
                    _usercfg["General"]["defaultsitemapPath"].StringValue = cb_SitexmlPath.Text;
                }

                _usercfg["General"]["site"].StringValueArray = cb_Site.Items.SourceCollection.Cast<string>().ToArray();

                _usercfg["General"]["SitexmlPath"].StringValueArray = cb_SitexmlPath.Items.SourceCollection.Cast<string>().ToArray();


                _usercfg["General"]["token"].StringValue = tb_Token.Text;
                _usercfg["General"]["type"].StringValue = chk_IsOriginal.IsChecked == true ? "original" : string.Empty;

                _usercfg.SaveToFile(path);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 推送
        /// 示例：
        /// http://blog.csdn.net/mojocube/article/details/47208409
        /// http://www.jb51.net/article/90054.htm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Push_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                const string hosturl = "http://data.zz.baidu.com";
                const string actionurl = "/urls";
                var param = string.Format("?site={0}&token={1}", cb_Site.Text, tb_Token.Text);
                if (chk_IsOriginal.IsChecked ?? false)
                {
                    param += "&type=original";
                }
                var url = hosturl + actionurl + param;

                var str = new StringContent(tb_PostContentUrl.Text);

                var pushresponse = await Client.PostAsync(url, str);
                if (pushresponse.StatusCode == System.Net.HttpStatusCode.OK)
                {

                }
                else
                {

                }
                tb_PostResponse.Text = await pushresponse.Content.ReadAsStringAsync();

                //记录已经提交的
                if (lstUrlsWaitCommit.Count > 0)
                {
                    File.WriteAllLines(fileUrls, lstUrlsWaitCommit.ToArray());
                    //File.Copy(fileUrls, Path.Combine(Properties.Settings.Default.SitemapPath, fileUrls), true);
                    File.Copy(fileUrls, fileUrlsHaveCommit, true);

                    #region 提交数据给Baidu
                    //Process.Start("curl_baidu.bat");
                    #endregion
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show("推送异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 界面链接打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

        private void btn_UrlAdd_Click(object sender, RoutedEventArgs e)
        {
            var sbUrlContents = new StringBuilder();
            var result = File.ReadAllText(cb_SitexmlPath.SelectedItem.ToString(), Encoding.UTF8);
            if (string.IsNullOrWhiteSpace(result))
            {
                MessageBox.Show("Sitemap.xml无内容", "无内容", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            #region 取出URL是到urls.txt中
            if (File.Exists(fileUrlsHaveCommit))
            {
                lstUrlsHaveCommit.AddRange(File.ReadAllLines(fileUrlsHaveCommit));
            }
            foreach (Match m in Regex.Matches(result, patternUrls))
            {
                var url = m.Value.TrimStart(@"</loc>".ToCharArray()).TrimEnd(@"</loc>".ToCharArray());
                if (!lstUrlsHaveCommit.Contains(url))
                {
                    lstUrlsWaitCommit.Add(url);
                    sbUrlContents.Append(url + Environment.NewLine);
                    //Console.WriteLine("'{0}' found at index {1}.", url, m.Index);
                }
            }

            tb_PostContentUrl.Text = sbUrlContents.ToString();
            //if (lstUrlsWaitCommit.Count > 0)
            //{
            //    File.WriteAllLines(fileUrls, lstUrlsWaitCommit.ToArray());
            //    //File.Copy(fileUrls, Path.Combine(Properties.Settings.Default.SitemapPath, fileUrls), true);
            //    File.Copy(fileUrls, fileUrlsHaveCommit, true);

            //    #region 提交数据给Baidu
            //    //Process.Start("curl_baidu.bat");
            //    #endregion
            //}
            strMsg = "可提交URL数量为：" + lstUrlsWaitCommit.Count;
            //Log.InfoLog(ip, strMsg);
            Console.WriteLine(strMsg);
            #endregion
        }

        private void btn_AddSitemap_Click(object sender, RoutedEventArgs e)
        {
            var win = new WindowAddSite { Owner = this };
            if (!(win.ShowDialog() ?? false)) return;
            cb_SitexmlPath.Items.Add(win.NewSite);
            btn_SaveConfig_Click(sender, e);
        }

    }
}
